package topicDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import usersDao.DBUtils;
import usersDao.UsersEntity;

public class MySqlTopicDao implements TopicDAO {

	@Override
	public int add(TopicEntity topic) {
		String sql = "insert into topic (tname) values (?)";
		return DBUtils.executeUpdate(sql, topic.getTname());
	}

	@Override
	public int del(long id) {
		String sql = "delete from topic where tid=?";
		return DBUtils.executeUpdate(sql, id);
	}

	@Override
	public int update(TopicEntity topic) {
		String sql = "update topic set tname=? where tid=?";
		return DBUtils.executeUpdate(sql, topic.getTname(), topic.getTid());
	}

	@Override
	public TopicEntity find(long id) {
		Connection conn = null;
		PreparedStatement prs = null;
		ResultSet rs = null;
		TopicEntity topic = null;
		String sql = "select * from topic where tid=?";
		try {
			conn = DBUtils.getConnection();
			prs = conn.prepareStatement(sql);
			prs.setLong(1, id);
			rs = prs.executeQuery();
			if (rs.next()) {
				topic = new TopicEntity();
				topic.setTid(rs.getLong("tid"));
				topic.setTname(rs.getString("tname"));
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.close(rs, prs, conn);
		}
		return topic;
	}

	@Override
	public List<TopicEntity> findAll() {
		List<TopicEntity> list = new ArrayList<TopicEntity>();
		Connection conn = null;
		PreparedStatement prs = null;
		ResultSet rs = null;
		TopicEntity toipc = null;
		String sql = "select * from topic";
		try {
			conn = DBUtils.getConnection();
			prs = conn.prepareStatement(sql);
			rs = prs.executeQuery();
			while (rs.next()) {
				toipc = new TopicEntity();
				toipc.setTid(rs.getLong("tid"));
				toipc.setTname(rs.getString("tname"));
				list.add(toipc);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.close(rs, prs, conn);
		}
		return list;
	}

	@Override
	public TopicEntity findTopTopic() {
		TopicEntity t = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		String sql = "";
		Connection conn = null;
		try {
			conn = DBUtils.getConnection();
			st = conn.prepareStatement(sql);
			rs = st.executeQuery();
			if (rs.next()) {
				t = new TopicEntity();
				t.setTid(rs.getInt("tid"));
				t.setTname(rs.getString("tname"));
			}
		} catch (SQLException ex) {
			ex.printStackTrace();
		} finally {
			DBUtils.close(rs, st, conn);
		}
		return t;
	}
}
